import {
  createRouter,
  createWebHistory
} from 'vue-router';
// import HomeView from '../views/HomeView.vue'

import axios from '../js/axiosself';



const whiteList = ['Login', 'Signup', 'Test', 'Test2',];
// 放行白名单


const routes = [{
    path: '/',
    name: 'home',
    component: () => import('../views/Main/MianView.vue')
  },
  {
    path: '/Test',
    name: 'Test',
    // component: () => import('../views/Main/RoleView.vue')
    component: () => import('../views/Main/user/RolePathView.vue')
  },
  {
    path: '/about',
    name: 'about',
    component: () => import( /* webpackChunkName: "about" */ '../views/AboutView.vue')
  }, {
    path: '/Signup',
    name: 'Signup',
    component: () => import('../views/LandS/SignUpView.vue')
  }, {
    path: '/Login',
    name: 'Login',
    component: () => import('../views/LandS/LoginView.vue')
  }, {
    path: '/Main',
    name: 'Main',
    component: () => import('../views/Main/MianView.vue'),
    children: [{
        path: '',
        component: () => import('../views/AboutView.vue')
      }, //默认主页
      {
        path: 'Publish',
        component: () => import('../views/Main/PublishBookView.vue')
      },
      {
        path: 'Root',
        component: () => import('../views/Main/user/RootView.vue')
      },
      {
        path: 'User',
        component: () => import('../views/Main/user/UserView.vue')
      }, 
      {
        path: 'Role',
        component: () => import('../views/Main/user/RoleView.vue')
      }, 
      {
        path: 'UserRole',
        component: () => import('../views/Main/user/UserRoleView.vue')
      },  
      {
        path: 'RolePath',
        component: () => import('../views/Main/user/RolePathView.vue')
      },  
    ]
  },
  // { path: '/:pathMatch(.*)*', name: 'NotFound', component: () => import('../views/NotFound.vue') },
];



// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 动态获取用户允许访问的路由列表（带缓存）
const getUserAllowedRoutes = async () => {
  const cachedRoutes = localStorage.getItem('allowedRoutes'); // 从缓存中读取
  if (cachedRoutes) {
    // return cachedRoutes.split(',').map(s => s.trim()); // 使用split分割并去除可能的空格; // 返回缓存的路由列表
    return cachedRoutes;
  }

  try {
    const response = await axios.get('/rolePath/allowedRoutes'); // 请求后端接口
    if(response.data.code==1){
    const routes = response.data.data?.allowedRoutes;
    localStorage.setItem('allowedRoutes', routes); // 缓存到 localStorage
    return routes.split(',').map(s => s.trim());
    }else{
      return [];
    }
  } catch (error) {
    console.error('获取用户允许的路由列表失败:', error);
    return [];
  }
};


// 创建路由守卫
// 添加导航守卫
router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('token');

  if (whiteList.includes(to.name)) { //对白名单的界面不拦截
    next();
    return;
  }
  if (to.path === '/' || to.path === '/Main') {
    next({
      path: '/Main/Publish'
    }); // 重定向到 /Main/Rpublist
    return;
  }

  // 如果没有 token，跳转到登录页
  if (!token) {
    console.log('无Token，需要登录');
    next({
      name: 'Login'
    });
    return;
  }


  // 动态获取用户允许访问的路由列表（优先使用缓存）
  const allowedRoutes = await getUserAllowedRoutes();
  console.log(allowedRoutes);
  console.log(to.name);
  
  
  // 检查用户是否有权限访问目标路由
  if (allowedRoutes.includes(to.path)) {
    next(); // 允许访问
  } else {
    console.log('无权限访问该页面');
    next({
      name: 'Login'
    }); // 跳转到登录界面
  }
});


export default router
